package com.yuancheng.modules.msweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuancheng.modules.msweb.entity.Operator;
import com.yuancheng.modules.msweb.entity.OperatorDevice;
import com.yuancheng.modules.msweb.mapper.OperatorMapper;
import com.yuancheng.modules.msweb.service.IOperatorDeviceService;
import com.yuancheng.modules.msweb.service.IOperatorService;
import com.yuancheng.modules.online.cgreport.util.StringUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 操作员
 * @author： yuancheng
 * @date：   2020-01-08
 * @version： V1.0
 */
@Service
public class OperatorServiceImpl extends ServiceImpl<OperatorMapper, Operator> implements IOperatorService {

    @Resource
    private IOperatorDeviceService operatorDeviceService;

    @Override
    public boolean operatorAdd(Operator operator) {
        String devnums = operator.getDevnums();
        int isSuccess = this.baseMapper.insert(operator);
        if(isSuccess>0 && !StringUtil.isEmpty(devnums)){
            String[] devnumArr = devnums.split(",");
            List<OperatorDevice> deviceList = new ArrayList<>();
            for(int i=0;i<devnumArr.length;i++){
                OperatorDevice operatorDevice = new OperatorDevice();
                operatorDevice.setDevnum(devnumArr[i]);
                operatorDevice.setOperatorId(operator.getId());
                deviceList.add(operatorDevice);
            }
            operatorDeviceService.saveBatch(deviceList);
        }
        return isSuccess>0?true:false;
    }

    @Override
    public boolean operatorUpdate(Operator operator) {
        String devnums = operator.getDevnums();
        int isSuccess = this.baseMapper.updateById(operator);
        if(isSuccess>0 && devnums != null){
            QueryWrapper wrapper = new QueryWrapper<OperatorDevice>();
            wrapper.eq("operator_id",operator.getId());
            if(operatorDeviceService.remove(wrapper)){
                String[] devnumArr = {};
                if(!StringUtil.isEmpty(devnums)){
                    devnumArr = devnums.split(",");
                }
                List<OperatorDevice> deviceList = new ArrayList<>();
                if(devnumArr.length > 0){
                    for(int i=0;i<devnumArr.length;i++){
                        OperatorDevice operatorDevice = new OperatorDevice();
                        operatorDevice.setDevnum(devnumArr[i]);
                        operatorDevice.setOperatorId(operator.getId());
                        deviceList.add(operatorDevice);
                    }
                    operatorDeviceService.saveBatch(deviceList);
                }
            }
        }
        return isSuccess>0?true:false;
    }
}
